import sys
import os
from django.conf import settings
from django.urls import reverse
from django.shortcuts import render
from django.conf.urls import url
from django.http import HttpResponse, HttpResponseBadRequest
from django.core.wsgi import get_wsgi_application
from django import forms
from django.core.cache import cache
from PIL import Image, ImageDraw
from io import BytesIO
import hashlib
from django.views.decorators.http import etag

# 定义基本的路径
BASE_DIR = os.path.dirname(__file__)
# 从环境变量中获取DEBUG 的配置 默认为True
DEBUG = os.environ.get("DEBUG", "on") == "on"

# Django 的配置修改 
settings.configure(
    DEBUG=DEBUG,
    SECRET_KEY="",
    # 加载url
    ROOT_URLCONF=__name__,
    # 域名信息
    ALLOWED_HOSTS=["*"],
    # 加载中间件
    MIDDLEWARE_CLASSES=(
        "django.middleware.common.CommonMiddleware",
        #"django.middleware.clickjacking.XFrameOptionsMiddleware"
    ),
    #
    INSTALLED_APPS=("django.contrib.staticfiles",),
    # 模板文件
    TEMPLATES = [{
                    "BACKEND": "django.template.backends.django.DjangoTemplates",
                    "DIRS": [os.path.join(BASE_DIR, "templates")]
                }],
    # 静态文件信息
    STATICFILES_DIRS=(os.path.join(BASE_DIR, 'static'), ),
    # 静态文件的url前缀
    STATIC_URL='/static/',
)

# 首页
def index(request):
    # 加载 placeholder 的url 加载 width 和 height 
    example = reverse("placeholder", kwargs={"width": 50, "height": 50})
    # 返回信息
    content = {
        "example": request.build_absolute_uri(example)
    }
    print(content)
    # 返回模板文件 index.html 
    return render(request, "index.html", content)


# ImageForm 配置
class ImageForm(forms.Form):
    # 设置 height 和 width 的范围
    height = forms.IntegerField(min_value=1, max_value=2000)
    width = forms.IntegerField(min_value=1, max_value=2000)
    
    # 生成图片
    def generate(self, image_format="PNG"):
        height = self.cleaned_data['height']
        width = self.cleaned_data['width']
        # 文件在缓存中的 key
        key = "{}_{}_{}".format(width, height, image_format)
        # 获取缓存
        content = cache.get(key)
        if content is None:
            # 缓存不存在 生成图片
            image = Image.new("RGB", (width, height))
            draw = ImageDraw.Draw(image)
            text = "{} x {}".format(width, height)
            textwidth, textheight = draw.textsize(text)
            if textwidth < width and textheight < height:
                texttop = (height - textheight) // 2
                textleft = (width - textwidth) // 2
                draw.text((textleft, texttop), text, fill=(255, 255, 255))

            content = BytesIO()
            image.save(content, image_format)
            content.seek(0)
            # 将生成的占位图片 放入缓存
            cache.set(key, content, 60 * 60)
        return content

# 浏览器缓存
def generate_etag(request, width, height):
    contet = "Placeholder: {0} x {1}".format(width, height)
    return hashlib.sha1(contet.encode("utf-8")).hexdigest()


@etag(generate_etag)
def placeholder(request, width, height):
    form = ImageForm({"height": height, "width": width})
    # 检查传入参数的正确性
    if form.is_valid():
        image = form.generate()
        return HttpResponse(image, content_type="image/png")
    else:
        return HttpResponseBadRequest("error")


urlpatterns = (
    url(r"^$", index, name="index"),
    url(r"^image/(?P<width>[0-9]+)/(?P<height>[0-9]+)/$", placeholder, name="placeholder")
)

# uwsgi 配置
application = get_wsgi_application()

if __name__ == '__main__':
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
